package org.nmgyjt.springboot.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nimbusds.jose.JOSEException;
import org.apache.commons.lang.StringUtils;
import org.nmgyjt.springboot.beans.admin.*;
import org.nmgyjt.springboot.entity.ApiRes;
import org.nmgyjt.springboot.entity.admin.CsSystemAdmin;
import org.nmgyjt.springboot.entity.admin.IDAASDeptResponse;
import org.nmgyjt.springboot.entity.admin.IDAASUserResponse;
import org.nmgyjt.springboot.entity.admin.UserInfo;
import org.nmgyjt.springboot.service.ICsSystemUserService;
import org.nmgyjt.springboot.service.impl.CsSystemAdminServiceImpl;
import org.nmgyjt.springboot.utils.HttpUtils;
import org.nmgyjt.springboot.utils.IDAASUserUtils;
import org.nmgyjt.springboot.utils.NMGYJTIDAASTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/cs/u")
@CrossOrigin
public class CsSystemUserController {

    @Autowired
    private ICsSystemUserService userService;

    @Autowired
    CsSystemAdminServiceImpl adminServiceImpl;

    @PostMapping("/list")
    public ApiRes getList(@RequestBody CsSystemUserSelectBean bean) throws ParseException, JOSEException {

        if (StringUtils.isEmpty(bean.getCreatedBy())) {
            return ApiRes.ok(new ArrayList<>());
        }
        return ApiRes.ok(userService.selectCsSystemUser(bean));
    }


    @PostMapping("/exist")
    public ApiRes checkUser(@RequestBody @Validated CsSystemUserCreateBean bean) throws ParseException, JOSEException {
        UserInfo userInfo = IDAASUserUtils.selectUserInfoFromIDAASByOpenIdV2(bean.getPhone());
        if (StringUtils.isEmpty(bean.getId())) {
            bean.setId("");
        }

        if (null != userInfo) {
            if (bean.getId().equals(userInfo.getId()) || "INACTIVE".equals(userInfo.getValues().getStatus())) {
                return ApiRes.ok();
            } else {
                HashMap<String, String> headerParams = new HashMap<>();
                headerParams.put("Content-Type", "application/json");
                headerParams.put("Authorization", "Bearer " + NMGYJTIDAASTokenUtils.getToken());
                Map<String, String> bodyParam2 = new HashMap();
                bodyParam2.put("object_type", "DEPT");
                String clientPostRes = HttpUtils.httpGet(
                        "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + userInfo.getValues().getDeptId() + "/traces",
                        bodyParam2, headerParams);
                List<IDAASDeptResponse> listResponse = JSONArray.parseArray(clientPostRes, IDAASDeptResponse.class);
                String orgName = "";
                if (null != listResponse && listResponse.size() > 2) {

                    orgName = listResponse.get(listResponse.size() - 1).getValues().getName() +
                            "--" + listResponse.get(listResponse.size() - 2).getValues().getName() +
                            "--" + listResponse.get(listResponse.size() - 3).getValues().getName();

                } else if (null != listResponse && listResponse.size() > 1) {
                    orgName = listResponse.get(listResponse.size() - 1).getValues().getName() +
                            "--" + listResponse.get(listResponse.size() - 2).getValues().getName();
                } else if (null != listResponse && listResponse.size() > 0) {
                    orgName = listResponse.get(listResponse.size() - 1).getValues().getName();
                }
                List<CsSystemAdmin> systemAdmins = adminServiceImpl.list(new LambdaQueryWrapper<CsSystemAdmin>().eq(CsSystemAdmin::getOrgId, userInfo.getValues().getDeptId()));
                Map<String, String> info = new HashMap<>();
                info.put("orgName", "\"" + orgName + "\"");
                if (null != systemAdmins && !CollectionUtils.isEmpty(systemAdmins)) {
                    info.put("name", systemAdmins.get(0).getName());
                    info.put("phone", systemAdmins.get(0).getPhone());
                } else {
                    info.put("name", "");
                    info.put("phone", "");
                }
                return ApiRes.ok(info);
            }
        }

        return ApiRes.ok();
    }

    @PostMapping("/new")
    public ApiRes createUser(@RequestBody @Validated CsSystemUserCreateBean bean) throws ParseException, JOSEException {
       /* UserInfo loginAdminInfo = IDAASUserUtils.selectUserInfoFromIDAASByOpenId(bean.getPhone());
        if (!ObjectUtils.isEmpty(loginAdminInfo)) {
            return ApiRes.fail(500, "用户已经存在,创建失败!");
        }*/
        if (StringUtils.isEmpty(bean.getOrgID()) && StringUtils.isEmpty(bean.getDepId())) {
            return ApiRes.fail(400, "管理员登录的部门参数缺失,创建人员失败,请联系系统管理员处理!");
        }
        if(StringUtils.isEmpty(bean.getOrgID()) && StringUtils.isNotEmpty(bean.getDepId())){
            bean.setOrgID(bean.getDepId());
        }

        if ("1000000007".equals(bean.getMenuID())) {
            HashMap<String, String> headerParams = new HashMap<>();
            headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());
            headerParams.put("Content-Type", "application/json");

            HashMap<String, String> bodyParams = new HashMap<>();
            bodyParams.put("object_type", "DEPT");
            String url = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + bean.getOrgID();
            String clientPostRes = HttpUtils.httpGet(url, bodyParams, headerParams);
            IDAASDeptResponse orgInfo = JSONObject.parseObject(clientPostRes, IDAASDeptResponse.class);

            Map bodyParam2 = new HashMap();
            bodyParam2.put("status", new ArrayList<>());

            List<String> orgIds = new ArrayList<>();
            orgIds.add(bean.getOrgID());
            bodyParam2.put("deptId", orgIds);
            bodyParam2.put("identityClassification", "defaultIdentityClassification");
            Map bodyParams1 = new HashMap();
            bodyParams1.put("objectType", "USER");
            bodyParams1.put("values", bodyParam2);

            String url2 = "http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/top_user/" + bean.getOrgID() + "/query?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str2 = HttpUtils.sendHttpPost(url2, (JSONObject) JSON.toJSON(bodyParams1), headerParams);
            IDAASUserResponse userResponse = JSONObject.parseObject(str2, IDAASUserResponse.class);
            if (userResponse.getTotal() + 1 > orgInfo.getValues().getMaxUserNumber()) {
                return ApiRes.fail(410, "部门人数已经饱和,添加人员失败!");
            }
        }
        UserInfo user = userService.createCsSystemUser(bean);
        return ApiRes.ok(user.getId());
    }

    @PostMapping("/ud")
    public ApiRes udOrder(@RequestBody @Validated List<CsSystemUdOrderBean> udOrders) throws ParseException, JOSEException {
        userService.udOrderCsSystemUser(udOrders);
        return ApiRes.ok();

    }

    @PostMapping("/update")
   // @CacheEvict(cacheNames = "selectUserInfoFromIDAASByOpenIdV2",allEntries = true)
    public ApiRes updateUser(@RequestBody CsSystemUserCreateBean bean) throws ParseException, JOSEException {
        UserInfo loginAdminInfo = IDAASUserUtils.selectUserInfoFromIDAASByOpenIdV2(bean.getCreatedBy());
        if (ObjectUtils.isEmpty(loginAdminInfo)) {
            return ApiRes.fail(500, "管理员不存在,更新失败!");
        }

        if (StringUtils.isEmpty(bean.getOrgID()) && StringUtils.isEmpty(bean.getDepId())) {
            return ApiRes.fail(400, "管理员登录的部门参数缺失,创建人员失败,请联系系统管理员处理!");
        }
        if(StringUtils.isNotEmpty(bean.getDepId()))
        bean.setOrgID(bean.getDepId());
        return ApiRes.ok(userService.updateCsSystemUser(bean, loginAdminInfo));
    }

    @PostMapping("/delete")
    public ApiRes deleteUser(@RequestBody CsSystemDeleteBean bean) throws ParseException, JOSEException {
        if (!ObjectUtils.isEmpty(bean)) {
            return ApiRes.ok(userService.deleteCsSystemUser(bean));
        }
        return ApiRes.fail(400, "删除参数异常,删除失败!");
    }
}
